package com.lbb.waimai.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.alibaba.fastjson.support.hsf.HSFJSONUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.JsonObject;
import com.lbb.waimai.entiry.Category;
import com.lbb.waimai.entiry.base.RedisKeyConstants;
import com.lbb.waimai.mapper.CategoryMapper;
import com.lbb.waimai.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@EnableTransactionManagement
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;



//    @Transactional
//    @Override
//    public String getCategorylist() {
//        //先去redis中查询，如果有则返回
//        String categorys = stringRedisTemplate.opsForValue().get(RedisKeyConstants.CATEGORY_LIST);
//        if(StringUtils.isEmpty(categorys)){
//            //如果没有则写入redis缓存
//            List<Category> categories = baseMapper.selectList(null);
//            Object json = JSONObject.toJSON(categories);
//            stringRedisTemplate.opsForValue().set(RedisKeyConstants.CATEGORY_LIST,json.toString());
//            return json.toString();
//        }else {
//        //如果有则直接返回数据
//            return  categorys;
//        }
//    }

    @Override
    public List<Category> getCategorylist() {
        //先从redis中取数据
        String categorys = stringRedisTemplate.opsForValue().get(RedisKeyConstants.CATEGORY_LIST);
        if(StringUtils.isEmpty(categorys)){

            //如果为空，去数据库查询
            List<Category> categories = baseMapper.selectList(null);
            //设置进redis
            stringRedisTemplate.opsForValue().set(RedisKeyConstants.CATEGORY_LIST, JSONObject.toJSONString(categories));
            return categories;
        }else {
            //redis中有数据
            List<Category> list = JSONObject.parseObject(categorys, List.class);
            return list;
        }
    }

    //执行redis更新策略
    @Transactional
    @Override
    public void update(Category category) {
        //先更新数据库，在删redis
        baseMapper.updateById(category);
        stringRedisTemplate.delete(RedisKeyConstants.CATEGORY_LIST);
    }
}
